<?php

namespace app\index\controller;
use app\commons\model\SaleVerifyer;
use app\commons\model\Member;
use app\commons\model\Sale;
use think\exception\ValidateException;

class Verifyer
{
    /**
     * 核销员列表
     */
    public function index(SaleVerifyer $saleVerifyer){
        $data = request()->param();
        if(!isset($data['id'])) throw new ValidateException('参数错误！');
        $list = $saleVerifyer->where(['sale_id'=>$data['id']])->order('id desc')->with(['member'])->paginate(10,false,['query'=>request()->param()]);
        return jsonp($list);
    }

    /**
     * 添加核销员
     */
    public function create(SaleVerifyer $saleVerifyer){
        $data = request()->param();
        if(!isset($data['member_id']))  throw new ValidateException('参数错误！');
        if(!isset($data['sale_id']))  throw new ValidateException('参数错误！');
        $member = Member::where(['id'=>$data['member_id']])->value('id');
        if(!$member)  throw new ValidateException('用户不存在！');
        $sale = Sale::where(['id'=>$data['sale_id'],'member_id'=>session('user')])->value('id');
        if(!$sale)  throw new ValidateException('非法操作！');
        //添加核销员
        $res = $saleVerifyer->allowField(true)->sale($data);
        if(!$res) throw new ValidateException('添加失败！');
        return jsonp();
    }

    /**
     * 删除核销员
     */
    public function delete(){
        $data = request()->param();
        if(!isset($data['id']))  throw new ValidateException('参数错误！');
        $info = SaleVerifyer::where(['id'=>$data['id']])->find();
        if(!$info) throw new ValidateException('核销员不存在！');
        $sale = Sale::where(['id'=>$info['sale_id'],'member_id'=>session('user')])->value('id');
        if(!$sale) throw new ValidateException('只能操作当前商家的核销员！');
        $id = $data['id'];
        $res = SaleVerifyer::destroy(function ($query) use ($id){
            $query->where(['id'=>$id]);
        });
        if(!$res) throw new ValidateException('删除失败！');
        return jsonp();
    }
}